import { dayjs } from 'element-plus'
import { isString } from 'lodash-es'

export default function useDateRange<
  T extends { begin_at: number | string; end_at: number | string }
>(queryParams: T) {
  // 日期区间
  const dateRange = ref()
  // 快捷日期
  const activeDay = ref<number | string>(0)

  // 时间选区间择器值改变，对快捷日期置空
  function onDateRangeChange() {
    if (!dateRange.value) {
      activeDay.value = -1
      setDateRange()
    } else {
      activeDay.value = ''
      setParams()
    }
  }

  // 选择日期变动，对外面参数进行重新赋值
  function setParams() {
    if (!dateRange.value) {
      return
    }
    const [start, end] = dateRange.value! || []
    if (!start || !end) {
      queryParams.begin_at = ''
      queryParams.end_at = ''
      return
    }

    if (dayjs(start).toString() === dayjs(end).toString()) {
      queryParams.begin_at = getUnix(start, false)
      queryParams.end_at = getUnix(start, true)
      return
    }
    queryParams.begin_at = dayjs(start).unix()
    queryParams.end_at = dayjs(end).unix()
  }

  // 设置起始时间和截止时间
  function setDateRange() {
    let start: dayjs.Dayjs
    let end: dayjs.Dayjs

    if (Number(activeDay.value) < 0) {
      start = dayjs().add(activeDay.value as number, 'day')
      start = start.set('hour', 0).set('minute', 0).set('second', 0)
      end = dayjs()
        .subtract(1, 'day')
        .set('hour', 23)
        .set('minute', 59)
        .set('second', 59)
    } else {
      start = dayjs().set('hour', 0).set('minute', 0).set('second', 0)
      end = dayjs().add(activeDay.value as number, 'day')
      end = end.set('hour', 23).set('minute', 59).set('second', 59)
    }
    dateRange.value = [start.toDate(), end.toDate()]
    setParams()
  }

  // 快捷日期改变，进行时间区间参数重新赋值，初始默认执行
  watch(
    activeDay,
    () => {
      if (isString(activeDay.value) && !activeDay.value) {
        return
      }
      setDateRange()
    },
    { immediate: true }
  )

  return {
    dateRange,
    activeDay,
    onDateRangeChange
  }
}
